package top.api.handler.security;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import top.api.common.ResponseResult;
import top.api.enums.AppHttpCodeEnum;
import top.api.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 */
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint{
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ResponseResult result = null;

        if (e instanceof InsufficientAuthenticationException){
            // InsufficientAuthenticationException  访问此资源需要完全身份验证
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else if (e instanceof BadCredentialsException){
            // BadCredentialsException  用户名或密码错误
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR,e.getMessage());
        }else {
            // 用户名不存在等等
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
        }
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
        log.error(e.toString());
    }
}
